<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        tbody {
            text-align: center;
        }
    </style>

</head>

<body>
    <button id="addBtn">添加一条新的访客信息</button>

    <table border=1 cellspacing=0 cellpadding=10 ;>
        <tbody>
            <tr>
                <th>序列号</th>
                <th>姓名</th>
                <th>年龄</th>
                <th>操作</th>
            </tr>

            <!-- 达到的目标：点击新增 -->
            <!-- <tr>
                <td>1</td>
                <td>名</td>
                <td>年龄</td>
                <td>按钮</td>
            </tr> -->

        </tbody>
    </table>

    <script>
        var info = [{
            name: "胡杭",
            age: 16
        }, {
            name: "胜明",
            age: 22
        }, {
            name: "军毅",
            age: 21
        }, {
            name: "晓华",
            age: 13
        }, {
            name: "盛聪",
            age: 23
        }, {
            name: "侦剑",
            age: 32
        }, {
            name: "红翔",
            age: 25
        }, {
            name: "超维",
            age: 18
        }, {
            name: "士琪",
            age: 22
        }, {
            name: "艳华",
            age: 20
        }];

        let tbody = document.querySelector('tbody');
        let addBtn = document.getElementById('addBtn');
        let index = 0; //模拟点击后，每次自增1
        let delBtn = tbody.querySelectorAll('button')

        addBtn.onclick = function() {
            // console.log('测试按钮有没有绑定成功');
            console.log(index);
            //当前index值要小于数组长度，否则会报错，获取不到数组的值
            if (index < info.length) {
                let newTr = document.createElement('tr'); //创建tr标签

                newTr.innerHTML = `
                <td>${index+1}</td>
                <td>${info[index].name}</td>
                <td>${info[index].age}</td>
                <td><button>删除</button></td>
                `;

                //过程
                // newTr.innerHTML = `
                // <td>1</td> ——→ <td>${index+1}</td>
                // <td>胡杭</td> ——→ <td>${info[0].name}</td> ——→ <td>${info[index].name}</td>
                // <td>16</td> ——→ <td>${info[0].age}</td> ——→ <td>${info[index].age}</td>
                // <td><button>删除</button></td>`;

                //将新的tr添加到tbody
                tbody.appendChild(newTr);

                //删除单个信息
                delBtn = tbody.querySelectorAll('button');
                //每个删除绑定事件
                delBtn.forEach(function(el) {

                    el.onclick = function() {
                        // console.log(el);//测试
                        el.parentElement.parentElement.remove();
                    }

                })

                index++; //因为下标最初是0，所以得第一次之后再+1
            }

        }
    </script>
</body>

</html>